/**
 * 
 */
package com.peycash.monitoring.fachada.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.peycash.monitoring.dominio.Sms;
import com.peycash.monitoring.fachada.FachadaException;
import com.peycash.monitoring.fachada.SMSFachada;
import com.peycash.monitoring.servicio.SMSServicio;
import com.peycash.monitoring.servicio.ServicioException;
import com.peycash.monitoring.utils.Config;
import com.peycash.monitoring.utils.Constantes;
import com.peycash.monitoring.ws.ClientRegister;

/**
 * @author JAMARO
 * 
 */
@Component
public class SMSFachadaImpl implements SMSFachada {

	@Autowired
	private SMSServicio servicioSms;
	private Config config = Config.getInstance();

	private final Logger LOGGER = LoggerFactory.getLogger(SMSFachadaImpl.class);

	@Override
	@Scheduled(cron = "*/10 * * * * ?")
	public void enviaSMS() throws FachadaException {
		try {
			List<Sms> listPendings = servicioSms.findPendings();
			for (Sms s : listPendings) {
				if (s.getNumEnvStatus().equals(
						Constantes.SMS_NUM_ENVIA_STATUS_REGISTRADO)) { 
					if (config.registerReceiveSMS()) {
						if (s.getNumRecibeStatus().equals(
								Constantes.SMS_NUM_ENVIA_STATUS_REGISTRADO)) {
							sensSMS(s);
						}
					} else {
						sensSMS(s);
					}
				}
			}
		} catch (ServicioException e) {
			LOGGER.error("Error en doRegisterAndSendSMS:" + e.getMessage(), e);
		}
	}

	private void sensSMS(Sms s) throws ServicioException {
		 String response = servicioSms.sendSms(s.getNumCelRec().toString(),
		 s.getSmsCont());
		//String response = "SMS_SENT";
		s.setRespServiceSms(response);
		servicioSms.updateSMS(s);
		LOGGER.debug("SMS ENVIADO ::: {} ::: ", s.getNumCelRec());
	}
}
